package com.sfh.gd.converter;

import com.power.common.util.StringUtil;
import com.sfh.gd.domain.dto.GameEditDTO;
import com.sfh.gd.domain.dto.GameRuleDTO;
import com.sfh.gd.domain.entity.GameDO;
import com.sfh.gd.domain.dto.GameNewDTO;
import com.sfh.gd.domain.entity.GameTeamDO;
import com.sfh.gd.domain.entity.MemberDO;
import com.sfh.gd.domain.vo.GameScoreSortVO;
import com.sfh.gd.domain.vo.GameVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.util.ArrayList;
import java.util.List;

@Mapper(componentModel = "spring")
public interface GameConverter {
    GameConverter INSTANCE = Mappers.getMapper(GameConverter.class);

    GameDO doToDO(GameNewDTO vo);

    @Mapping(target = "gameId", source = "id")
    GameDO doToDO(GameEditDTO vo);

    @Mapping(target = "id", source = "gameId")
    GameVO doToVO(GameDO gameDO);

    @Mapping(target = "id", source = "teamId")
    @Mapping(target = "memberNameList", expression = "java(mapMemberNames(gameDO))")
    GameScoreSortVO doToVO(GameTeamDO gameDO);

    List<GameScoreSortVO>  doToVO(List<GameTeamDO>  gameDO);

    // ✅ 辅助方法：组装成员名称（昵称优先，缺失则使用手机号）
    default List<String> mapMemberNames(GameTeamDO gameDO) {
        List<String> names = new ArrayList<>();
        MemberDO member1 = gameDO.getMember1();
        MemberDO member2 = gameDO.getMember2();

        if (member1 != null) {
          if (StringUtil.isNotEmpty(member1.getNickName())){
              names.add(member1.getNickName());
          }else if (StringUtil.isNotEmpty(member1.getPhoneNum())){
              names.add(member1.getPhoneNum());
          }
        }

        if (member2 != null) {
            if (StringUtil.isNotEmpty(member2.getNickName())){
                names.add(member2.getNickName());
            }else if (StringUtil.isNotEmpty(member2.getPhoneNum())){
                names.add(member2.getPhoneNum());
            }
        }
        return names;
    }

    GameRuleDTO gameRuleJsonToDTO(String ruleJson);
}
